# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpRequest,HttpResponse,JsonResponse
from django.shortcuts import render
from django.core.paginator import Paginator
from saltcore.tasks import host_sync_update,host_sync_create
from minions.models import Minions_status
from returner.models import Salt_grains
from django.db.models import Q
from website import JSONResponseMixin
from django.views.generic import *
from cmdb.models import *
import logging
import json
import datetime
from utils import *


# Create your views here.

def List_Host(request):
    if request.method == "GET":
       source_d = IpSource.objects.all()
       hostgroup_d = HostGroup.objects.all()
       project_d = Project.objects.all()

    return render(request, 'cmdb/host.list.html', {'source': source_d, 'project': project_d,'group': hostgroup_d })


def show_host_in_table(request):

    if request.method == "GET":
        print(request.GET)
        limit = request.GET.get('pageSize')  # how many items per page
        offset = request.GET.get('page')  # current Page
        search = request.GET.get('search')
        sort_column = request.GET.get('sortName')  # which column need to sort
        order = request.GET.get('sortOrder')  # ascending or descending

        vlan_type = request.GET.get('txt_search_vlan_type[]')
        project_type = request.GET.get('txt_search_project_type[]')
        group_type = request.GET.get('txt_search_group_type[]')
        status_type = request.GET.get('txt_search_status_type[]')

        kwargs = {
            # 动态查询的字段
        }

        if vlan_type is not None:
             kwargs["env"] = vlan_type

        if project_type is not None:
             kwargs["project"] = project_type

        if group_type is not None:
             kwargs["group"] = group_type

        if status_type is not None:
             kwargs["status"] = status_type


        di = {
            "hostname__contains": search,
            "ip__contains": search,
        }
        if search:
            q = Q()
            for i in di:
                q.add(Q(**{i: di[i]}), Q.OR)
            #args = Q(hostname__contains=search) | Q(ip__contains=search) | Q(asset_no__contains=search)
            if kwargs != '':
                for k in kwargs:
                    q.add(Q(**{k: kwargs[k]}), Q.AND)
                all_records = Host.objects.filter(q)
            else:
                all_records = Host.objects.filter(q)
        elif kwargs != '':
             q = Q()
             for k in kwargs:
                q.add(Q(**{k: kwargs[k]}), Q.AND)
             all_records = Host.objects.filter(q)
        else:
            all_records = Host.objects.all()  # must be wirte the line code here
        if sort_column:  # 判断是否有排序需求
            sort_column = sort_column.replace('host_', '')
            if sort_column in ['hostname','ip','cpu_num']:  # 如果排序的列表在这些内容里面
                if order == 'desc':  # 如果排序是反向
                    sort_column = '-%s' % (sort_column)
                all_records = all_records.order_by(sort_column)
        all_records_count = all_records.count()

        if not offset:
            offset = 0
        if not limit:
            limit = 20  # 默认是每页20行的内容，与前端默认行数一致
        pageinator = Paginator(all_records, limit)  # 开始做分页

        page = int(int(offset) / int(limit) + 1)
        response_data = {'total': all_records_count, 'rows': []}  # 必须带有rows和total这2个key，total表示总页数，rows表示每行的内容

        for Hosts in pageinator.page(page):
            # 下面这些Host_开头的key，都是我们在前端定义好了的，前后端必须一致，前端才能接受到数据并且请求.
            response_data['rows'].append({
                "host_id": Hosts.id if Hosts.id else "",
                "host_hostname": Hosts.hostname if Hosts.hostname else "",
                "host_ip": Hosts.ip if Hosts.ip else "",
                "host_vlan": Hosts.env.vlan_id if Hosts.env else "",
                "host_project": Hosts.project.id if Hosts.project else "",
                "host_env": Hosts.env.env.fullname if Hosts.env else "",
                "host_vip": Hosts.vip if Hosts.vip else "",
                "host_kernel": Hosts.kernel if Hosts.kernel else "",
                "host_kernel_release": Hosts.kernel_release if Hosts.kernel_release else "",
                "host_ilo_ip": Hosts.ilo_ip if Hosts.ilo_ip else "",
                "host_group": Hosts.group.id if Hosts.group.id else "",
                "host_asset_no": Hosts.asset_no if Hosts.asset_no else "",
                "host_asset_type": Hosts.asset_type if Hosts.asset_type else "",
                "host_status": Hosts.status if Hosts.status else "" ,
                "host_os": Hosts.os if Hosts.os else "",
                "host_vendor": Hosts.vendor if Hosts.vendor else "",
                "host_uuid": Hosts.uuid if Hosts.uuid  else "",
                "host_cpu_model": Hosts.cpu_model if Hosts.cpu_model else "",
                "host_cpu_num":Hosts.cpu_num if Hosts.cpu_num else "" ,
                "host_memory": Hosts.memory if Hosts.memory else "",
                "host_disk": Hosts.disk if Hosts.disk else "",
                "host_disks": Hosts.disks if Hosts.disks else "",
                "host_sn": Hosts.sn if Hosts.sn else "",
                "host_location": Hosts.position if Hosts.position else "",
                "host_memo": Hosts.memo if Hosts.memo else "",
                "host_create_time": str(datetime.datetime.strftime(Hosts.create_time, "%Y-%m-%d %H:%M")) if Hosts.create_time else "",
                "host_update_time": str(datetime.datetime.strftime(Hosts.update_time, "%Y-%m-%d %H:%M")) if Hosts.update_time else "",
                "host_terminal_time": str(datetime.datetime.strftime(Hosts.terminal_time, "%Y-%m-%d %H:%M")) if Hosts.terminal_time else "",
            })

        return HttpResponse(json.dumps(response_data))


def sync_asset_to_host(request):
    if request.method == "GET":
        salt_grains = Salt_grains.objects.all()
        new_minion_list = []
        old_minion_list = []

        for salt_host in salt_grains:
            minion = salt_host.minion_id
            print minion
            cmdb_host = Host.objects.filter(hostname=minion)
            if cmdb_host:
               old_minion_list.append(minion)
            else:
               new_minion_list.append(minion)
        print new_minion_list
        print old_minion_list
        response_data = {
            "new_minion": new_minion_list,
            "old_minion": old_minion_list,
        }
        host_sync_update(old_minion_list)
        host_sync_create(new_minion_list)

        return HttpResponse(json.dumps(response_data))


def cmdb_host_create(request):
    print request.POST
    if request.method == "POST":
        host_hostname = request.POST.get("host_hostname")
        host_os = request.POST.get("host_os")
        host_ip = request.POST.get("host_ip")
        host_sn = request.POST.get("host_sn")
        host_kernel = request.POST.get("host_kernel")
        host_kernel_release = request.POST.get("host_kernel_release")
        host_manufacturer = request.POST.get("host_manufacturer")
        host_cpu_model = request.POST.get("host_kernel_release")
        host_num_cpus = request.POST.get("host_num_cpus")
        host_disk_total = request.POST.get("host_disk_total")
        host_disks = request.POST.get("host_disks")
        host_memory = request.POST.get("host_memory")
        host_uuid = request.POST.get("host_uuid")
        host_ilo = request.POST.get("host_ilo")
        host_vip = request.POST.get("host_vip")
        host_asset_no = request.POST.get("host_asset_no")
        host_group = request.POST.get("host_group")
        host_project = request.POST.get("host_project")
        host_terminal_time = request.POST.get("host_terminal_time")

        host = Host()
        host.vendor = host_manufacturer
        host.hostname = host_hostname      #s1-sit-admin-web01
        host_cpu_model = host_cpu_model
        host.ip = host_ip
        host.sn = host_sn
        host.kernel = host_kernel   #3.10.1211
        host.kernel_release = host_kernel_release    #7.2.3.112.
        host.cpu_model = host_cpu_model
        host.cpu_num = host_num_cpus
        host.disk = host_disk_total
        host.disks = host_disks
        host.memory = host_memory
        host.uuid = host_uuid
        host.os = host_kernel #Linux or Windows
        host.env = IpSource.objects.get(id=env_dispatch(host_ip))
        host.asset_type = Manufactory_dispatch(host_manufacturer)
        host.ilo_ip = host_ilo
        host.vip = host_vip
        host.asset_no = host_asset_no
        host.os = host_os #CentOS
        host.group = HostGroup.objects.get(id=host_group)
        host.project = Project.objects.get(id=host_project)
        host.terminal_time = host_terminal_time
        host.status = 1
        host.save()
        return JsonResponse({"msg":"success"})

def cmdb_host_update(request,pk):
    print request.POST
    if request.method == "POST":
        host_hostname = request.POST.get("host_hostname")
        host_os = request.POST.get("host_os")
        host_ip = request.POST.get("host_ip")
        host_sn = request.POST.get("host_sn")
        host_kernel = request.POST.get("host_kernel")
        host_kernel_release = request.POST.get("host_kernel_release")
        host_manufacturer = request.POST.get("host_manufacturer")
        host_cpu_model = request.POST.get("host_cpu_model")
        host_num_cpus = request.POST.get("host_num_cpus")
        host_disk_total = request.POST.get("host_disk_total")
        host_disks = request.POST.get("host_disks")
        host_memory = request.POST.get("host_memory")
        host_uuid = request.POST.get("host_uuid")
        host_ilo = request.POST.get("host_ilo")
        host_vip = request.POST.get("host_vip")
        host_asset_no = request.POST.get("host_asset_no")
        host_asset_type = request.POST.get("host_asset_type")
        host_group = request.POST.get("host_group")
        host_project = request.POST.get("host_project")
        if request.POST.get("host_terminal_time"):
           host_terminal_time = request.POST.get("host_terminal_time")
        else:
           host_terminal_time = None
        host_status = request.POST.get("host_status")

        host = Host.objects.filter(pk=pk)
        try:
            host.update(hostname=host_hostname,
                        vendor=host_manufacturer,
                        ip=host_ip,
                        sn=host_sn,
                        cpu_model=host_cpu_model,
                        os=host_os,
                        memory=host_memory,
                        kernel=host_kernel,
                        kernel_release=host_kernel_release,
                        env_id=env_dispatch(host_ip),
                        cpu_num=host_num_cpus,
                        disk=host_disk_total,
                        disks=host_disks,
                        uuid=host_uuid,
                        ilo_ip=host_ilo,
                        vip=host_vip,
                        asset_no=host_asset_no,
                        asset_type=host_asset_type,
                        terminal_time=host_terminal_time,
                        group_id=host_group,
                        project_id=host_project,
                        status=host_status
                        )
        except Exception as e:
            print e

    return JsonResponse({"msg": 'success'})

def cmdb_host_delete(request, pk):
    print request.POST
    if request.method == "POST":
       host = Host.objects.filter(pk=pk)
       try:
         host.delete()
       except Exception as e:
         print e

    return JsonResponse({"msg": 'success'})




